package com.lw.spring.javademo.login;


import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private  static final String USERNAME = "liuwei";
    private  static final String PASSWORD = "123456";
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        // 验证用户名和密码
        Map<String, String> registeredUsers = com.lw.spring.javademo.register.RegisterServlet.getRegisteredUsers();

        if (registeredUsers.containsKey(username) && registeredUsers.get(username).equals(password)) {
            // 登录成功
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            response.sendRedirect("index.jsp");
        } else {
            // 登录失败
            response.getWriter().println("<html><body><h3 style='color:red;'>用户名或密码错误！</h3></body></html>");
        }

        // Hello

        out.println("<html><body>");
        out.println("<h1>" + "Do your HomeWork!!!!" + "</h1>");
        out.println("</body></html>");
    }
}

